<script setup lang="ts">
import { addPatientApi, getPatientInfoByIdAPI, putPatientUpdateAPI } from '@/apis/patient'
import type { PatientUpdateParams } from '@/types/patient'
import { ref, watch } from 'vue'

const form = ref<UniHelper.UniFormsInstance>()
const formData = ref<PatientUpdateParams>({
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 1,
})

const formRules = ref<UniHelper.UniFormsRules>({
  name: {
    rules: [
      { required: true, errorMessage: '请填写患者姓名' },
      { pattern: /^(?:[\u4e00-\u9fa5·]{2,16})$/, errorMessage: '请输入正确的姓名' },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请填写身份证号' },
      {
        pattern:
          /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
        errorMessage: '请输入正确的身份证号',
      },
    ],
  },
  gender: {
    rules: [
      { required: true, errorMessage: '请选择患者性别' },
      //自定义校验
      {
        validateFunction: (rule, value, data, callback) => {
          const idCardGenderNumber = formData.value.idCard.charAt(16)
          if (Number(idCardGenderNumber) % 2 !== value) {
            callback('请选择正确的性别')
          }
          return true
        },
      },
    ],
  },
})
// 监听身份证号，自动设置性别
watch(
  () => formData.value.idCard,
  (newVal) => {
    if (newVal.length >= 17) {
      const genderNum = newVal.charAt(16)
      formData.value.gender = Number(genderNum) % 2
    }
  }
)

const params = defineProps<{
  id?: string
}>()
const validateForm = async () => {
  try {
    await form.value?.validate?.()
    if (params.id) {
      const { name, idCard, defaultFlag, id, gender } = formData.value
      await putPatientUpdateAPI({ name, idCard, defaultFlag, id, gender })
    } else {
      await addPatientApi(formData.value)
    }
    // #ifdef H5
    // H5端的返回上一页
    window.history.back()
    // #endif

    // #ifdef MP-WEIXIN
    // 跳转回患者列表页，H5端偶尔出现兼容性问题
    uni.navigateBack()
    // #endif
    // 提示用户
  } catch (error) {}
}

const onSwitchChange = (e: UniHelper.SwitchOnChangeEvent) => {
  formData.value.defaultFlag = e.detail.value ? 1 : 0
}

uni.setNavigationBarTitle({ title: params.id ? '编辑患者' : '添加患者' })
const getPatientInfoById = async () => {
  if (params.id) {
    const res = await getPatientInfoByIdAPI(params.id)
    formData.value = {
      ...formData.value,
      ...res.data,
      gender: res.data.gender ?? 1,
    }
  }
}
getPatientInfoById()
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="form" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{
              color: '#121826',
              backgroundColor: '#F5F5F5',
              disableColor: '#F5F5F5',
              borderColor: 'transparent',
            }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{
              color: '#121826',
              backgroundColor: '#F5F5F5',
              disableColor: '#F5F5F5',
              borderColor: 'transparent',
            }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人">
          <view class="uni-switch">
            <switch
              color="#20c6b2"
              style="transform: scale(0.7)"
              @change="onSwitchChange"
              :checked="formData.defaultFlag === 1"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="validateForm">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
  {{ formData }}
</template>

<style lang="scss">
@import './index.scss';
</style>
